<template>
  <div class="question-detail-page">
    <el-container>
      <el-header>
        <nav-bar></nav-bar>
      </el-header>
      <el-main>
        <div class="question-container" v-loading="loading">
          <div v-if="error" class="error-message">
            <el-alert
              :title="error"
              type="error"
              @close="error = ''"
            />
          </div>

          <template v-else-if="question">
            <div class="question-header">
              <h1 class="title">{{ question.title }}</h1>
              <div class="meta">
                <div class="author-info">
                  <el-avatar 
                    :size="40" 
                    :src="question.author.avatar || getAvatarUrl(question.author.username)"
                  ></el-avatar>
                  <div class="author-meta">
                    <span class="username">{{ question.author.username }}</span>
                    <div class="time-info">
                      <span class="time">提问于 {{ formatDate(question.createdAt) }}</span>
                      <span class="time" v-if="question.updatedAt !== question.createdAt">
                        · 更新于 {{ formatDate(question.updatedAt) }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="status-and-tags">
                  <el-tag
                    :type="question.status === 'open' ? 'success' : 'info'"
                    effect="dark"
                    class="status-tag"
                  >
                    {{ question.status === 'open' ? '进行中' : '已解决' }}
                  </el-tag>
                  <div class="tags">
                    <el-tag
                      v-for="tag in question.tags"
                      :key="tag"
                      size="small"
                      effect="plain"
                      class="tag"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>

            <div class="question-content">
              <p>{{ question.content }}</p>
            </div>

            <div class="answers-section">
              <h2>{{ question.answers.length }} 个回答</h2>
              
              <div v-if="question.answers.length === 0" class="no-answers">
                <el-empty description="暂无回答">
                  <el-button type="primary" @click="showAnswerForm = true">写回答</el-button>
                </el-empty>
              </div>

              <div v-else class="answer-list">
                <el-card v-for="answer in question.answers" :key="answer._id" class="answer-card">
                  <div class="answer-header">
                    <div class="author-info">
                      <el-avatar 
                        :size="32" 
                        :src="answer.author.avatar || getAvatarUrl(answer.author.username)"
                      ></el-avatar>
                      <div class="author-meta">
                        <span class="username">{{ answer.author.username }}</span>
                        <span class="time">回答于 {{ formatDate(answer.createdAt) }}</span>
                      </div>
                    </div>
                    <div class="answer-actions">
                      <el-tag 
                        v-if="answer.isAccepted" 
                        type="success" 
                        effect="dark"
                        class="accepted-tag"
                      >
                        <el-icon><Check /></el-icon> 已采纳
                      </el-tag>
                      <el-button 
                        v-else-if="canAcceptAnswer(answer)"
                        type="success" 
                        :icon="Select"
                        plain
                        size="small"
                        @click="handleAcceptAnswer(answer)"
                      >
                        采纳该回答
                      </el-button>
                    </div>
                  </div>
                  <div class="answer-content">
                    {{ answer.content }}
                  </div>
                </el-card>
              </div>
            </div>

            <div class="answer-form" v-if="isAuthenticated">
              <el-button 
                type="primary" 
                @click="showAnswerForm = true"
                v-if="!showAnswerForm"
              >
                写回答
              </el-button>

              <el-card v-if="showAnswerForm">
                <template #header>
                  <div class="answer-form-header">
                    <span>写回答</span>
                    <el-button text @click="showAnswerForm = false">取消</el-button>
                  </div>
                </template>
                <el-form
                  ref="answerFormRef"
                  :model="answerForm"
                  :rules="answerRules"
                >
                  <el-form-item prop="content">
                    <el-input
                      v-model="answerForm.content"
                      type="textarea"
                      :rows="6"
                      placeholder="写下你的回答..."
                      maxlength="1000"
                      show-word-limit
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button 
                      type="primary" 
                      @click="submitAnswer"
                      :loading="submitting"
                    >
                      提交回答
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </template>
        </div>
      </el-main>
      <el-footer>
        <footer-component></footer-component>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Select } from '@element-plus/icons-vue'
import NavBar from '../components/NavBar.vue'
import FooterComponent from '../components/FooterComponent.vue'
import { getQuestionById, createAnswer, acceptAnswer } from '../api/qa'

export default {
  name: 'QuestionDetail',
  components: {
    NavBar,
    FooterComponent,
    Check
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const error = ref('')
    const question = ref(null)
    const showAnswerForm = ref(false)
    const answerFormRef = ref(null)
    const submitting = ref(false)

    const answerForm = ref({
      content: ''
    })

    const answerRules = {
      content: [
        { required: true, message: '请输入回答内容', trigger: 'blur' },
        { min: 10, message: '回答不能少于10个字符', trigger: 'blur' }
      ]
    }

    const isAuthenticated = computed(() => store.getters.isAuthenticated)
    console.log('认证状态:', isAuthenticated.value)
    
    const currentUser = computed(() => store.getters.currentUser)
    console.log('当前用户信息:', currentUser.value)

    const fetchQuestion = async () => {
      console.log('开始获取');
      
      loading.value = true
      error.value = ''
      try {
        const res = await getQuestionById(route.params.id)
        console.log('获取到的问题数据：', res)
        
        // 标准化数据结构
        const questionData = res.qa.question || {}
        question.value = {
          id: res.qa._id,
          title: questionData.title,
          content: questionData.content,
          author: {
            _id: questionData.author?._id,
            username: questionData.author?.username,
            avatar: questionData.author?.avatar
          },
          createdAt: questionData.createdAt,
          tags: questionData.tags || [],
          answers: (res.qa.answers || []).map(answer => ({
            _id: answer._id,
            content: answer.content,
            author: answer.author || {},
            createdAt: answer.createdAt,
            isAccepted: answer.isAccept || false
          })),
          status: res.qa.status,
          updatedAt: res.qa.updatedAt
        }
        
        console.log('处理后的数据：', question.value)
      } catch (err) {
        console.error('获取问题详情错误:', err)
        error.value = err.message || '获取问题详情失败'
      } finally {
        loading.value = false
      }
    }

    const formatDate = (date) => {
      if (!date) return '未知时间'
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const getAvatarUrl = (username) => {
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random`
    }

    const checkAuth = async () => {
      console.log('检查认证状态:', {
        isAuthenticated: isAuthenticated.value,
        hasToken: !!localStorage.getItem('token')
      })

      if (isAuthenticated.value) {
        try {
          const res = await store.dispatch('fetchUserInfo')
          console.log('获取用户信息成功:', res)
          if (!currentUser.value?._id) {
            throw new Error('用户信息不完整')
          }
        } catch (err) {
          console.error('获取用户信息失败:', err)
          store.dispatch('logout')
          ElMessage.warning('登录已过期，请重新登录')
        }
      }
    }

    const canAcceptAnswer = (answer) => {
      console.log('检查采纳权限:', {
        isAuthenticated: isAuthenticated.value,
        currentUser: currentUser.value,
        hasToken: !!localStorage.getItem('token')
      })
      
      if (!isAuthenticated.value || !currentUser.value?._id) {
        console.log('用户未登录或用户信息未加载', {
          isAuthenticated: isAuthenticated.value,
          currentUser: currentUser.value
        })
        return false
      }

      if (!question.value) {
        console.log('问题数据未加载')
        return false
      }
      
      const currentUserId = currentUser.value._id
      const authorId = question.value.author._id
      console.log('权限检查:', {
        currentUserId,
        authorId,
        questionStatus: question.value.status
      })
      
      const isQuestionAuthor = currentUserId === authorId
      const canAccept = question.value.status === 'open' && isQuestionAuthor
      console.log('采纳权限检查结果:', {
        isQuestionAuthor,
        canAccept
      })
      return canAccept
    }

    const handleAcceptAnswer = async (answer) => {
      if (!isAuthenticated.value) {
        ElMessage.warning('请先登录')
        return
      }

      if (!currentUser.value?._id) {
        ElMessage.warning('用户信息未加载，请刷新页面')
        return
      }

      try {
        await ElMessageBox.confirm(
          '你确定要采纳该回答吗？',
          '确认采纳',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await acceptAnswer(question.value.id, answer._id)
        ElMessage.success('已采纳回答')
        await fetchQuestion()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('采纳回答失败:', error)
          ElMessage.error(error.message || '操作失败，请重试')
        }
      }
    }

    const submitAnswer = async () => {
      if (!isAuthenticated.value) {
        ElMessage.warning('请先登录')
        return
      }

      if (!currentUser.value?._id) {
        ElMessage.warning('用户信息未加载，请刷新页面')
        return
      }

      if (!answerFormRef.value) return

      try {
        await answerFormRef.value.validate()
        submitting.value = true

        await createAnswer(question.value.id, {
          content: answerForm.value.content.trim(),
          author: currentUser.value._id
        })

        ElMessage.success('回答发布成功')
        showAnswerForm.value = false
        answerForm.value.content = ''
        await fetchQuestion()
      } catch (error) {
        console.error('提交回答失败:', error)
        ElMessage.error(error.message || '发布失败，请重试')
      } finally {
        submitting.value = false
      }
    }

    onMounted(async () => {
      await checkAuth()
      await fetchQuestion()
    })

    return {
      question,
      loading,
      error,
      showAnswerForm,
      answerForm,
      answerFormRef,
      answerRules,
      submitting,
      isAuthenticated,
      currentUser,
      formatDate,
      getAvatarUrl,
      submitAnswer,
      canAcceptAnswer,
      handleAcceptAnswer,
      Select,
      Check
    }
  }
}
</script>

<style scoped>
.question-detail-page {
  min-height: 100vh;
}

.el-header {
  padding: 0;
  height: auto;
}

.el-main {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.question-container {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.question-header {
  margin-bottom: 30px;
}

.title {
  margin: 0 0 20px;
  font-size: 24px;
  color: #303133;
}

.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-meta {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #303133;
}

.time {
  font-size: 0.9em;
  color: #909399;
}

.time-info {
  display: flex;
  gap: 4px;
  color: #909399;
  font-size: 0.9em;
}

.status-and-tags {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-tag {
  font-weight: 500;
}

.tags {
  display: flex;
  gap: 8px;
}

.tag {
  cursor: pointer;
}

.question-content {
  font-size: 16px;
  line-height: 1.8;
  color: #303133;
  margin: 30px 0 40px;
  white-space: pre-wrap;
}

.answers-section {
  margin-top: 40px;
}

.answers-section h2 {
  margin-bottom: 20px;
  font-size: 18px;
  color: #303133;
}

.no-answers {
  padding: 40px 0;
}

.answer-card {
  margin-bottom: 20px;
}

.answer-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.answer-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.accepted-tag {
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.accepted-tag :deep(.el-icon) {
  margin-right: 2px;
}

.answer-content {
  color: #303133;
  line-height: 1.6;
  white-space: pre-wrap;
  margin-top: 12px;
}

.answer-form {
  margin-top: 40px;
}

.answer-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.error-message {
  margin: 20px 0;
}
</style> 